﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Net_SCADA;

namespace WZXC_GBL_QUERY
{
    public class NetLine
    {
          DataTable dtZoneSet;
          DataTable dtItemSet;

        public   Dictionary<int , Zone> zone { get; set; } = new Dictionary<int , Zone>();
        public   List<KeyTime> BoxKeyTime { get; private set; } = new List<KeyTime>();
        public   Dictionary<int , PVMaxMin> BoxMaxMin { get; set; } = new Dictionary<int , PVMaxMin>();
        public   Dictionary<string , NetEquip> Equip { get; set; } = new Dictionary<string , NetEquip>();
        public  Dictionary<int , Alarm> EquipAlarm { get; set; } = new Dictionary<int , Alarm>();
        public Dictionary<int, CurveSetting> LineSetting = new Dictionary<int, CurveSetting>();
        public Dictionary<int, PVMaxMin> pvmaxmin = new Dictionary<int, PVMaxMin>();
        public string LineName { get; set; } = "辊棒炉";
        public int[] KeytimeIndex{ get; private set; } = new int[10];
        public  void NetlineLoad()
        {
            LoadZoneSetting();
            LoadAlarmSet();
            LoadKeyTimeSet();
            LoadEquipSetting();
            LoadCurveSetting();
        }
        private void LoadCurveSetting()
        {
            foreach (int i in zone.Keys)
            {
                if (zone[i].isShowCurve)
                {
                    if (zone[i].pv != null)
                    {
                        LineSetting.Add(zone[i].pv.ID, new CurveSetting(zone[i].pv.ID));
                        pvmaxmin.Add(zone[i].pv.ID, new PVMaxMin() { zonename = zone[i].ZoneName });
                    }
                    if (zone[i].sv != null)
                    {
                        LineSetting.Add(zone[i].sv.ID, new CurveSetting(zone[i].sv.ID));
                    }
                    if (zone[i].ovpv != null)
                    {
                        LineSetting.Add(zone[i].ovpv.ID, new CurveSetting(zone[i].ovpv.ID));
                    }
                }
            }
        }
        public void LoadEquipSetting()
        {
            //从数据库加载设备相关的设置信息，包括设备的ID和名称
            DataTable dt = DBOperate.GetEquipSet();
            if (dt == null || dt.Rows.Count == 0) return;
            foreach (DataRow rw in dt.Rows)
            {
                Equip.Add(rw["equipid"].ToString(), new NetEquip()
                {
                    EquipName = rw["equipname"].ToString(),
                    EquipID = rw["equipid"].ToString(),
                    PassTime = Convert.ToSingle(rw["equipPassTime"])
                });
            }
        }

        public  void LoadKeyTimeSet()
        {
            //加载用来计算时间段之间的keytime
            Ini datasetting = new Ini(System.Windows.Forms.Application.StartupPath + @"\settings\DataSetting.dat");
            string[] arrString = datasetting.ReadValue("Keytime", "keytimeindex").Split(',');
            for (int i = 0; i < 10 && i< arrString.Length ; i++)
            {
                int.TryParse(arrString[i], out KeytimeIndex[i]);
            }

            datasetting = new Ini(System.Windows.Forms.Application.StartupPath + @"\settings\Setting.dat");
            LineName = datasetting.ReadValue("Printer", "LineName").Trim();

            //加载数据库的keytime配置内容
            DataTable dt =DBOperate.GetKeyTimeSet();
            if (dt == null || dt.Rows.Count == 0) return;
            for (int i = 0 ; i < dt.Rows.Count ; i++)
            {
                BoxKeyTime.Add(new KeyTime()
                {
                    KeyID = Convert.ToInt32(dt.Rows[i]["keytimeID"]),
                    KeyTimeName = dt.Rows[i]["keytimename"].ToString() ,
                    KeyTimeInIndex = Convert.ToInt32(dt.Rows[i]["keytimeinindex"]) ,
                    KeyTimeOutIndex = Convert.ToInt32(dt.Rows[i]["keytimeoutindex"])
                });
                BoxKeyTime.Last().SetZoneID(dt.Rows[i]["zoneid"].ToString());
                List<int> pos=SetPostionID(dt.Rows[i]["postionid"].ToString());
                BoxKeyTime.Last().PostionID = pos;
                for (int j = 0 ; j < pos.Count ; j++)
                {
                    foreach (int alid in EquipAlarm.Keys)
                    {
                        if (EquipAlarm[alid].AlarmPostion.Contains(pos[j]) && !BoxKeyTime.Last().Alarmid.Contains(alid))
                        {
                            BoxKeyTime.Last().Alarmid.Add(alid);
                            //break;
                        }
                    }
                }
                foreach (int item in BoxKeyTime.Last().keyZone.Keys)
                {
                    if (!BoxMaxMin.ContainsKey(item))
                        BoxMaxMin.Add(item , new PVMaxMin() { id = item });
                }
            }
        }

        public  List<int> SetPostionID(string ids)//从数据库中获取的，以逗号分隔的postionid
        {
            List<int> pos=new List<int>();
            if (ids.Length > 0)
            {
                string[] s=ids.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0 ; i < s.Length ; i++)
                {
                    if (int.TryParse(s[i] , out int v))
                    {
                        pos.Add(v);
                    }
                }
            }
            return pos;
        }
        public  void LoadAlarmSet()
        {
            DataTable dtAlarmSet = DBOperate.GetAlarmSet();
            if (dtAlarmSet == null || dtAlarmSet.Rows.Count == 0) return;
            for (int i = 0 ; i < dtAlarmSet.Rows.Count ; i++)
            {
                int id=Convert.ToInt32(dtAlarmSet.Rows[i]["alID"].ToString());
                EquipAlarm.Add(id,new Alarm()
                {
                    AlarmName = dtAlarmSet.Rows[i]["alName"].ToString() ,
                    AlarmID = id,
                    AlarmLevel = Convert.ToInt32(dtAlarmSet.Rows[i]["allevel"].ToString()) ,
                });
                EquipAlarm[id].SetAlarmPostion(dtAlarmSet.Rows[i]["postionid"].ToString());
            }
        }
        public  void LoadZoneSetting()
        {
            dtZoneSet = DBOperate.GetZoneSet();
            dtItemSet = DBOperate.GetItemSet();
            if (dtZoneSet == null || dtItemSet == null || dtItemSet.Rows.Count == 0 || dtZoneSet.Rows.Count == 0) return;
            for (int i = 0 ; i < dtZoneSet.Rows.Count ; i++)
            {
                if (int.TryParse(dtZoneSet.Rows[i]["zoneID"].ToString() , out int id))
                {
                    zone.Add(id , new Zone()
                    {
                        pv = SetZoneItem(i , "pvid") ,
                        sv = SetZoneItem(i , "svid") ,
                        ovpv = SetZoneItem(i , "ovpvid") ,
                        ovsv = SetZoneItem(i , "ovsvid") ,
                        ubais = SetZoneItem(i , "ubaisID") ,
                        lbais = SetZoneItem(i , "lbaisID") ,
                        diff = SetZoneItem(i , "diffid") ,
                        ZoneName = dtZoneSet.Rows[i]["zoneName"].ToString() ,
                        Unit = dtZoneSet.Rows[i]["unit"].ToString() ,
                        ID = Convert.ToInt32(dtZoneSet.Rows[i]["zoneID"].ToString()) ,
                        GroupID = Convert.ToInt32(dtZoneSet.Rows[i]["GroupID"].ToString()) ,
                        EquipID = dtZoneSet.Rows[i]["EquipID"].ToString() ,
                        isSV = Convert.ToInt32(dtZoneSet.Rows[i]["issv"].ToString()) == 1 ? true : false,
                        svtype = Convert.ToInt32(dtZoneSet.Rows[i]["svtype"].ToString()),
                    });
                }

                //Equip[zone.Last().EquipID].EquipZone.Add(zone.Last());
            }
        }
        private   Item SetZoneItem(int zoneindex , string itemid)
        {
            int id;
            int.TryParse(dtZoneSet.Rows[zoneindex][itemid].ToString() , out id);
            if (id > 0)
            {
                DataRow[] row= dtItemSet.Select("itemID="+id);
                if (row.Length > 0)
                {
                    return new Item()
                    {
                        ID = Convert.ToInt32(row[0]["itemID"].ToString()) ,
                        Add = row[0]["itemAdd"].ToString() ,
                        DataType = row[0]["Type"].ToString() ,
                        DP = Convert.ToInt32(row[0]["DP"].ToString()) ,
                        Min = Convert.ToSingle(row[0]["smin"].ToString()) ,
                        Max = Convert.ToSingle(row[0]["smax"].ToString()) ,
                        isRecord = row[0]["isRecord"].ToString() == "1" ? true : false ,
                        isShow = row[0]["isShow"].ToString() == "1" ? true : false
                    };
                }
            }
            return null;
        }
    }
}
